package com.tedu._06weibo.controller;

import com.tedu._06weibo.mapper.UserMapper;
import com.tedu._06weibo.pojo.dto.UserLoginDTO;
import com.tedu._06weibo.pojo.dto.UserRegDTO;
import com.tedu._06weibo.pojo.entity.User;
import com.tedu._06weibo.pojo.vo.UserVO;
import com.tedu._06weibo.result.JsonResult;
import com.tedu._06weibo.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    @ApiOperation("用户注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println("开始处理注册");
        if (userMapper.selectByUsername(userRegDTO.getUsername())!=null){
            return new JsonResult(Status.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.success();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.trace("UserController.login():begin");
        log.debug(userLoginDTO.toString());
        log.info("开始处理用户登录");
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        log.debug(user.toString());
        if (user==null){
            return new JsonResult(Status.USERNAME_ERROR);
        }else if (!user.getPassword().equals(userLoginDTO.getPassword())){
            return new JsonResult(Status.PASSWORD_ERROR);
        }
        session.setAttribute("user",user);
        return JsonResult.success();
    }

    @GetMapping("/currentUser")
    @ApiOperation("获取当前登录用户信息")
    public JsonResult currentUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return new JsonResult(Status.NOT_LOGIN);
        }else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return JsonResult.success(userVO);
        }
    }

    @GetMapping("/logout")
    @ApiOperation("用户登出")
    public JsonResult logOut(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.success();
    }


}
